from typing import Dict
from playwright.sync_api import (
    sync_playwright,
    APIResponse,
    Playwright,
    APIRequestContext,
)


class APIRequest:
    """负责发起API请求，所有的业务接口类都需要继承该类。"""

    _playwright: Playwright = sync_playwright().start()
    _request: APIRequestContext = _playwright.request.new_context()

    def __init__(self, url: str, header: dict, body: dict) -> None:
        """
        初始化，传入API请求信息
        :param url: 请求的URL
        :param header: 请求头
        :param body: 请求体
        """
        self._url = url
        self._header = header
        self._body = body

    @property
    def url(self) -> str:
        return self._url

    @property
    def header(self) -> dict:
        return self._header

    @header.setter
    def header(self, value) -> None:
        self._header = value

    @property
    def body(self) -> dict:
        return self._body

    @body.setter
    def body(self, value) -> None:
        self._body = value

    def post(self) -> Dict[APIResponse, None]:
        """发送POST请求"""
        res = self._request.post(url=self.url, headers=self.header, data=self.body)
        return res.json()
